package com.wlbx.agent.ui.activity;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.SPUtil;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;

public class ChangePwActivity extends BaseActivity {
    private static final String TAG = "ChangePwActivity";

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    @BindView(R.id.et_pw)
    EditText et_pw;
    @BindView(R.id.et_repw)
    EditText et_repw;
    @BindView(R.id.ll_check)
    LinearLayout ll_check;
    @BindView(R.id.iv_check)
    ImageView iv_check;
    private PopupWindow mPopuptipWindow;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_changepw;
    }

    @Override
    public void initData() {
        mTitleTV.setText("修改密码");
        et_pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
        et_repw.setTransformationMethod(PasswordTransformationMethod.getInstance());
        et_pw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(et_pw.getText().toString().length()>=8 && et_repw.getText().toString().length()>=8){
                    btSubmit.setEnabled(true);
                    btSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_en));
                }else{
                    btSubmit.setEnabled(false);
                    btSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_dis));
                }
            }
        });
        et_repw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(et_pw.getText().toString().length()>=8 && et_repw.getText().toString().length()>=8){
                    btSubmit.setEnabled(true);
                    btSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_en));
                }else{
                    btSubmit.setEnabled(false);
                    btSubmit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bt_dis));
                }
            }
        });
    }

    @Override
    public void initEvent() {}

    @OnClick({R.id.iv_layout_top_back,R.id.bt_submit,R.id.ll_check})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                finish();
                break;
            case R.id.bt_submit:
                if(isValidPw(et_pw.getText().toString()) && isValidPw(et_repw.getText().toString()) && samePw(et_pw.getText().toString(),et_repw.getText().toString())){
                    setPassWord();
                }
                break;
            case R.id.ll_check:
                if("select".equals(iv_check.getTag())){
                    iv_check.setTag("selected");
                    iv_check.setImageResource(R.mipmap.checked);
                    et_pw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    et_repw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    iv_check.setTag("select");
                    iv_check.setImageResource(R.mipmap.check);
                    et_pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    et_repw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            default:
                break;
        }
    }

    //设置密码
    public void setPassWord(){
        final Map<String, String> map = new HashMap<>();
        map.put("password", et_pw.getText().toString());
        map.put("rePassword", et_repw.getText().toString());
        Logger.i(TAG, JSON.toJSONString(map));
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .changePw(JSON.toJSONString(map))
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    showPopupTip();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                }else {
                    Toast.makeText(mActivity, rMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"修改密码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    //弹出提示框
    public void showPopupTip(){
        View view = mInflater.inflate(R.layout.pop_tip_change, null);
        mPopuptipWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mPopuptipWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPopuptipWindow.setOutsideTouchable(false);
        mPopuptipWindow.setFocusable(true);
        mPopuptipWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPopuptipWindow.setFocusable(false);
                mPopuptipWindow.dismiss();
                return true;
            }
        });
        mPopuptipWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //校验密码格式
    private boolean isValidPw(String pw){
        if (TextUtils.isEmpty(pw)){
            Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!pw.matches(Constant.PW_PATTERN)){
            Toast.makeText(this,"请输入正确格式的密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //检测两次输入一致
    private boolean samePw(String pw,String repw){
        if(!pw.equals(repw)){
            Toast.makeText(this,"两次输入密码不一致，请重新输入",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

}